package com.intelligy.service

import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import com.intelligy.util.MusicUtil


// 指令
const val KEY_COMMAND = "k_command"

// 位置
const val KEY_POSITION = "k_music_position"

// 音乐名称
const val KEY_MUSIC_NAME = "k_music_name"

// 音乐路径
const val KEY_MUSIC_PATH = "k_music_path"

// 播放位置
const val KEY_MUSIC_INDEX = "k_music_index"

// 音乐列表
const val KEY_MUSIC_LIST = "k_music_index"

// 总播放时长
const val MUSIC_TIME_TOTAL = "music_time_total"

// 当前进度
const val MUSIC_TIME_CURR = "music_time_curr"

// 播放进度更新的广播
const val CAST_ACTION_UPDATE = "com.intelligy.MUSIC_TIME_UPDATE"


const val CMD_INIT = 1000    // 初始化
const val CMD_PLAY = 1001    // 播放
const val CMD_PAUSE = 1002   // 暂停
const val CMD_NEXT = 1003    // 下一曲
const val CMD_PREV = 1004    // 上一曲
const val CMD_STOP = 1005    // 停止
const val CMD_RESUME = 1006  // 从暂停状态恢复
const val CMD_PLAY_TIME = 1007     // 从制定位置播放

class MusicService : Service() {

    lateinit var context: Context

    lateinit var musicUtil: MusicUtil

    override fun onCreate() {
        super.onCreate()
        this.context = this
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (intent == null) return super.onStartCommand(intent, flags, startId)

        intent.apply {
            val command = getIntExtra(KEY_COMMAND, -1)

            when (command) {
                CMD_INIT -> {
                    val musics = getStringArrayListExtra(KEY_MUSIC_LIST)
                    musicUtil = MusicUtil(context, musics ?: listOf())
                }
                CMD_PLAY -> {
                    val index = getIntExtra(KEY_MUSIC_INDEX, 0)
                    musicUtil.play(index)
                }
                CMD_PAUSE -> musicUtil.pause()
                CMD_RESUME -> musicUtil.play()
                CMD_NEXT -> musicUtil.next()
                CMD_PREV -> musicUtil.prev()
                CMD_STOP -> musicUtil.stop()
                CMD_PLAY_TIME -> {
                    val position = getIntExtra(KEY_POSITION, 0)
                    musicUtil.playOnTime(position)
                }
            }
        }

        return super.onStartCommand(intent, flags, startId)
    }
}